package com.auxgroup.smarthome.job;

import com.alibaba.fastjson.JSON;
import com.auxgroup.smarthome.repo.DeviceShareRelieveRepo;
import com.auxgroup.smarthome.service.inner.UserDeviceInnerService;
import com.auxgroup.smarthome.utils.NewDateUtils;
import com.auxgroup.smarthome.utils.common.LOG;
import com.auxgroup.smarthome.vo.DeviceShareRelieveVo;
import com.auxgroup.smarthome.web.ApiResponse;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @Author: laiqiuhua.
 * @Date: 2017/9/12 15:14.
 */
@Component
public class DeviceShareRelieveJob implements SimpleJob {
    @Autowired
    private DeviceShareRelieveRepo deviceShareRelieveRepo;
    @Autowired
    private UserDeviceInnerService userDeviceInnerService;

    @Override
    public void execute(ShardingContext shardingContext) {
        List<DeviceShareRelieveVo> deviceShareList = deviceShareRelieveRepo.getPartDataList(shardingContext.getShardingItem(),DeviceShareRelieveVo.class);
        LOG.info(this,shardingContext.getJobName() + "--分片No." + shardingContext.getShardingItem()
                + "获取好友解除分享任务缓存数据长度："+deviceShareList.size());
        if(deviceShareList == null || deviceShareList.size() == 0) return;
        deviceShareList.stream().forEach(deviceShare -> {
            String appid = deviceShare.getAppid();
            String token = deviceShare.getToken();
            String deviceId = deviceShare.getDeviceId();
            String uid = deviceShare.getUid();
            long expired = deviceShare.getExpiredAt();
            if (isExpired(expired)) {
                ApiResponse apiResponse = userDeviceInnerService.relieveFriendShare(appid, token, uid, deviceId);
                LOG.info(this, JSON.toJSONString(apiResponse));
            }
        });
    }

    private boolean isExpired(long expired) {
        LocalDateTime expiredLocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(expired), NewDateUtils.getBeijingZoneId());
        LocalDateTime now = LocalDateTime.now(NewDateUtils.getBeijingZoneId());
        LOG.info(this, "当前时间戳："+now.toEpochSecond(ZoneOffset.of("+8"))+"---当前时间："+now+"---过期时间戳："+expired+"---过期时间："+expiredLocalDateTime);
        if(now.isAfter(expiredLocalDateTime)) {
            return true;
        }
        return false;
    }

}
